package j20251105;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket=null;
    private int serverPort;
    private String serverIp;

    public UdpEchoClient(int serverPort, String serverIp) throws SocketException {
        this.serverPort = serverPort;
        this.serverIp = serverIp;
        socket=new DatagramSocket();
    }

    public void start() throws IOException {
        Scanner sc=new Scanner(System.in);
        while (true){
            //给出请求
            System.out.println("请输入请求：");
            if(!sc.hasNext()){
                break;
            }
            String request=sc.next();
            //将请求发给服务器
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),
                    request.getBytes().length, InetAddress.getByName(serverIp),serverPort);
            socket.send(requestPacket);
            //接收响应
            DatagramPacket responsePacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response=new String(responsePacket.getData(),0,responsePacket.getLength());
            //打印响应
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client=new UdpEchoClient(9090,"127.0.0.1");
        client.start();
    }
}
